<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类ID" prop="categoryId">
        <el-input
          v-model="queryParams.categoryId"
          placeholder="请输入所属分类ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产名称" prop="assetName">
        <el-input
          v-model="queryParams.assetName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物产编号" prop="assetCode">
        <el-input
          v-model="queryParams.assetCode"
          placeholder="请输入物产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购人" prop="purchaser">
        <el-input
          v-model="queryParams.purchaser"
          placeholder="请输入采购人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物产名称" align="center" prop="assetName" />
      <el-table-column label="物产编号" align="center" prop="assetCode" />
      <el-table-column label="物产类别" align="center" prop="categoryName" />
      <el-table-column label="采购金额" align="center" prop="purchaseAmount" />
      <el-table-column label="采购人" align="center" prop="purchaser" />
      <el-table-column label="采购时间" align="center" prop="purchaseTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="质保结束时间" align="center" prop="warrantyEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.warrantyEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="useStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.asset_info_status" :value="scope.row.useStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" max-height="60vh" class="flat-dialog" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="asset-form">
        <!-- 第一行：物产名称 + 物产类别 -->
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="物产名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入物产名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物产类别" prop="categoryId">
              <treeselect
                v-model="form.categoryId"
              :options="categoryOptions"
              :loading="categoryLoading"
              :normalizer="normalizer"
              placeholder="请选择物产类别"
              clearable
              style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：规格型号 + 物产编号 + 采购金额 -->
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物产编号" prop="assetCode">
              <el-input v-model="form.assetCode" placeholder="请输入物产" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购金额" prop="purchaseAmount">
              <el-input v-model="form.purchaseAmount" placeholder="请输入采购" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：采购时间 + 质保时间 + 采购人 + 使用状态-->
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="采购时间" prop="purchaseTime">
              <el-date-picker
                v-model="form.purchaseTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择采购时间"
                clearable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质保时间" prop="warrantyEndTime">
              <el-date-picker
                v-model="form.warrantyEndTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择质保时间"
                clearable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购人" prop="purchaser">
              <el-input v-model="form.purchaser" placeholder="请输入采购人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="使用状态" prop="useStatus">
              <el-select v-model="form.useStatus" placeholder="选择状态" clearable>
                <el-option
                  v-for="dict in dict.type.asset_info_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入内容"
                type="textarea"
                rows="3"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 附件上传 -->
<!--        <el-row>-->
<!--          <el-col :span="24">-->
<!--            <el-form-item label="附件">-->
<!--              <div class="attachment-container">-->
<!--                <el-upload-->
<!--                  action=""-->
<!--                  :before-upload="beforeUploadFile"-->
<!--                  :on-success="handleFileSuccess"-->
<!--                  :limit="1"-->
<!--                  class="attachment-upload"-->
<!--                >-->
<!--                  <el-button size="small" type="primary">选取文件</el-button>-->
<!--                </el-upload>-->
<!--                <div class="upload-tip">-->
<!--                  请上传大小不超过5MB 格式为doc/docx/xls/xlsx/ppt/pptx/txt/pdf的文件-->
<!--                </div>-->
<!--              </div>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right; padding-right: 20px;">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/kobe/asset/info"
import {parseTime} from "../../../../utils/ruoyi";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import {listType} from "@/api/system/dict/type";

export default {
  name: "Info",
  components: {Treeselect},
  dicts: ["asset_info_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产信息表格数据
      infoList: [],
      // 资产分类树选项
      categoryOptions: [],
      categoryLoading: false, // 加载状态
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        assetName: null,
        assetCode: null,
        purchaser: null,
        supplier: null,
      },
      // 表单参数
      form: {},
      // 资产分类树选择器表单参数
      categoryForm: null,
      // 表单校验
      rules: {
        categoryId: [
          {required: true, message: "所属分类ID不能为空", trigger: "blur"}
        ],
        assetName: [
          {required: true, message: "物产名称不能为空", trigger: "blur"}
        ],
        assetCode: [
          {required: true, message: "物产编号不能为空", trigger: "blur"}
        ],
        useStatus: [
          {required: true, message: "使用状态不能为空", trigger: "change"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        updateTime: [
          {required: true, message: "最后更新时间不能为空", trigger: "blur"}
        ],
        isDeleted: [
          {required: true, message: "逻辑删除不能为空", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadCategoryTree()
  },
  methods: {
    parseTime,
    /** 查询资产信息列表 */
    getList() {
      this.loading = true
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 加载物产类别树形数据
    loadCategoryTree() {
      this.categoryLoading = true;
      // 调用后端接口获取树形数据（替换为实际接口）
      listType().then(response => {
        this.categoryOptions = response.data; // 假设接口返回树形数组
        this.categoryLoading = false;
      })},
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    normalizer(node) {
        return {
          id: node.id,
          label: node.categoryName,
          children: node.children
        };
      },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        assetName: null,
        assetCode: null,
        purchaseAmount: null,
        purchaser: null,
        purchaseTime: null,
        warrantyEndTime: null,
        useStatus: null,
        supplier: null,
        specification: null,
        creator: null,
        parentId: null,
      },
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物产信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getInfo(row.id).then(response => {
        this.form = response.data
        // 确保使用状态回显为字典定义的字段名而不是数字
        if (this.form.useStatus !== null && this.form.useStatus !== undefined) {
          // 转换useStatus为字符串类型，确保与字典值匹配
          this.form.useStatus = String(this.form.useStatus)
          console.log('处理后的使用状态值:', this.form.useStatus)
        }
        this.open = true
        this.title = "修改物产信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 修改判断条件，支持检查undefined和null值
          if (this.form.id !== undefined && this.form.id !== null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除资产信息编号为"' + ids + '"的数据项？').then(function () {
        return delInfo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('asset/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
/* 修复布局错乱的样式 */
.asset-form {
  padding: 0 15px;
}

.el-form-item {
  margin-bottom: 15px;
}

/* 上传区域样式优化 */
.upload-container {
  margin-top: 5px;
}

.thumbnail-upload {
  width: 150px;
}

.upload-placeholder {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #8c8c8c;
}

.upload-tip {
  margin-top: 8px;
  color: #666;
  font-size: 12px;
  line-height: 1.5;
}

.attachment-container {
  margin-top: 5px;
}

/* 对话框样式优化 */
.flat-dialog .el-dialog__body {
  padding: 10px 20px;
  max-height: calc(60vh - 100px);
  overflow-y: auto;
}
</style>
